#Google App Engine's modules
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import db

#Group-written modules
from functions import *

#Parsing modules
from xml.dom.minidom import parseString
import cgi
import os
import gdata.youtube    
import gdata.youtube.service
import urlparse, xmlrpclib, subprocess
import sys

class ResultsHandler(webapp.RequestHandler):
  def post(self):
      path = os.path.join('templates', 'results')
      results = cgi.escape(self.request.get('content'))
      results = results.replace(' ', '+')
      user = users.get_current_user()
      logout_url = users.create_logout_url('/')  
      #gets ten videos from youtube and five from revver net
      #retrieving youtube videos
      url ="http://gdata.youtube.com/feeds/api/videos?q=" + results + "&orderby=relevance&prettyprint=true&max-results=10&v=2" 
      result = urlfetch.fetch(url=url, 
                          method=urlfetch.GET, 
                          headers={'Content-Type': 'text/html'})
      
      dom = parseString(result.content)
      playerCode = []
      thumbnails = []
      titles = []
      handleContent(dom,titles,playerCode,thumbnails)
      
      #retrieving revver net videos
      api_url = "https://api.revver.com/xml/1.0?login=teambeta&passwd=csce315"
      api = xmlrpclib.Server(api_url)
      query1 = {"search":[results]}
      returnFields = ["id","title","author","url","description","thumbnailUrl","flashMediaUrl"]
      options = {"limit":5}
      #tries twice and then passes if it still times out
      try:
        results2 = api.video.find(query1,returnFields,options)
      except:
        try:
          results2 = api.video.find(query1,returnFields,options)
        except:
          pass
      for i in results2:
          for key in i:
              if key == "title":
                  titles.append(unicode(i[key]).encode('utf-8','ignore'))
              if key == "id":
                  playerCode.append(unicode(i[key]).encode('utf-8','ignore'))
              if key == "thumbnailUrl":
                  thumbnails.append(unicode(i[key]).encode('utf-8','ignore'))

#end revver net
      
      zipped = zip(playerCode,titles,thumbnails)
      #lists of most popular videos
      c_url = []
      c_title = []
      #keep track of favorites
      user_favs = db.GqlQuery("SELECT * FROM Fav WHERE favOwn = :1",users.get_current_user())

      fav_title = []
      fav_url = []
      fav_code = []
    
      for favs in user_favs:
          fav_title.append(favs.title)
          fav_url.append(favs.vid_idx)
          fav_code.append(favs.code)                     

      template_values = { 
        'user': user,
        'logout': logout_url,
        'pageinfo':zipped,
        'favs': zip(fav_url[:10], fav_title[:10], fav_code[:10]),
      }

      path = os.path.join('templates', 'index.html') 
      self.response.out.write(template.render(path, template_values))
